package com.shuaiche.yeguan.util;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.shuaiche.yeguan.SCApplication;
import com.shuaiche.yeguan.util.BitmapUtil;
import com.shuaiche.yeguan.util.SCImageUrlUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * 类描述：图片保存到本地工具
 *
 * @auther: baoyinbo
 * @date: 2018/12/20 下午2:37
 */

public class SCSavePictureUtils {


    private static volatile SCSavePictureUtils instance = null;
    private SCSavePictureUtils () {

    }
    public static  SCSavePictureUtils getInstance(){
        if(instance==null){
            synchronized(SCSavePictureUtils.class){
                if(instance == null){
                    instance= new SCSavePictureUtils();
                }
            }
        }
        return instance;
    }

//    private KProgressHUD progressHUD;

    public void dismissProgressHUD(){
//        if (progressHUD != null && progressHUD.isShowing()) {
//            progressHUD.dismiss();
//        }
    }


    public void saveImage(final Context context, final List<String> urls, final Bitmap bitmap,
                          final SCSavePictureListener listener) {


        if (urls != null && urls.size() > 0) {
            final int size = urls.size();
//            progressHUD= KProgressHUD.create(context)
//                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
//                    .setCancellable(false)
//                    .setLabel("0/" + size)
//                    .setAnimationSpeed(2)
//                    .setDimAmount(0.5f)
//                    .setSize(120, 120);

            new AsyncTask<Void, Integer, Void>() {

                @Override
                protected Void doInBackground(Void... voids) {
                    for (int i = 0; i < urls.size(); i++) {
                        publishProgress(i + 1);
                        saveImage(context, urls.get(i), bitmap);
                    }
                    return null;
                }

                @Override
                protected void onProgressUpdate(Integer... values) {
                    super.onProgressUpdate(values);
//                    if (progressHUD != null) {
//                        progressHUD.setLabel("(" + values[0] + "/" + size + ")");
//                    }
                }

                @Override
                protected void onPostExecute(Void aVoid) {
                    super.onPostExecute(aVoid);
//                    if (progressHUD != null && progressHUD.isShowing()){
//                        progressHUD.dismiss();
//                    }
                    listener.onFinish();
                }

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
//                    if (progressHUD != null && !progressHUD.isShowing()) {
//                        progressHUD.show();
//                    }
                }
            }.execute();

        }
    }


    /**
     * 当url == sccache
     * 保存 Bitmap
     * @param context
     * @param url
     * @param bp
     */
    public void saveImage(Context context, String url, Bitmap bp) {
        Bitmap bitmap = null;
        if ("sccache".equals(url)) {
//        if (url.equals("sccache")) {
            bitmap = bp;
        } else {
            try {
                bitmap = Glide.with(context)
                        .asBitmap()
                        .load(SCImageUrlUtils.getImgUrl(url))
                        .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                        .get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

        BitmapUtil.bitmap2file(context, bitmap);
    }


    public static String saveImage(Context context, Bitmap bitmap) {
        if (bitmap != null) {
            File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();
            File appDir = new File(file, "sc");
            boolean createed = false;
            if (!appDir.exists()) {
                createed = appDir.mkdirs();
            }
            String fileName = System.currentTimeMillis() + ".png";
            File currentFile = new File(appDir, fileName);


            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            BufferedInputStream bis = null;
            File imageFile = null;
            try {
                bis = new BufferedInputStream(new ByteArrayInputStream(
                        stream.toByteArray()));
                imageFile = currentFile;
                fos = new FileOutputStream(imageFile);
                bos = new BufferedOutputStream(fos);
                byte[] b = new byte[1024];
                int length;
                while ((length = bis.read(b)) != -1) {
                    bos.write(b, 0, length);
                    bos.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (bis != null) {
                        bis.close();
                    }
                    if (bos != null) {
                        bos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            String path = currentFile.getPath();
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                    Uri.fromFile(new File(path))));
            return path;
        } else {
            return "";
        }
    }

}
